package com.dong.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.ROUTE_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SIMPLE_HOST_ROUTING_FILTER_ORDER;


/**
 * 路由过滤器在预过滤器之后运行，并向其他服务发出请求。此处的许多工作是在请求和响应数据与客户端所需的模型之间进行转换
 * 默认的实现为SimpleHostRoutingFilter ，这个一般情况没必要重写
 * 禁止默认的SimpleHostRoutingFilter 使用 context.setRouteHost(null);
 *
 * @author zhaodongchao
 * @date 2020/11/12 17:18
 */
@Component
public class MyRouteFilter extends ZuulFilter {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public String filterType() {
        return ROUTE_TYPE;
    }

    @Override
    public int filterOrder() {
        return SIMPLE_HOST_ROUTING_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        return RequestContext.getCurrentContext().getRouteHost() != null && RequestContext.getCurrentContext().sendZuulResponse();
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        logger.info("路由过滤器中请求路径为：{}", request.getRequestURI());
        return null;
    }
}
